[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  23. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  24. import type { CrowiRequest } from '~/interfaces/crowi-request';
  25. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  26. // import { useRendererSettings } from '~/stores/renderer';
  27. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  28. import type { EditorConfig } from '~/interfaces/editor-settings';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useEditingMarkdown } from '~/stores/editor';
  36. import { useSWRxCurrentPage, useSWRxIsGrantNormalized } from '~/stores/page';
  37. import { useRedirectFrom } from '~/stores/page-redirect';
  38. import {
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import loggerFactory from '~/utils/logger';
  43. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  44. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  45. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  46. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  49. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  50. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  51. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  52. import {
  53. useCurrentUser,
  54. useIsLatestRevision,
  55. useIsForbidden, useIsNotFound, useIsSharedUser,
  56. useIsEnabledStaleNotification, useIsIdenticalPath,
  57. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  58. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  59. useIsAclEnabled, useIsSearchPage, useTemplateTagData, useTemplateBodyData, useIsEnabledAttachTitleHeader,
  60. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  61. useIsSlackConfigured, useRendererConfig,
  62. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  63. } from '../stores/context';
  64. import {
  65. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  66. } from './utils/commons';
  67. // import { useCurrentPageSWR } from '../stores/page';
  68. declare global {
  69. // eslint-disable-next-line vars-on-top, no-var
  70. var globalEmitter: EventEmitter;
  71. }
  72. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  73. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  74. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  75. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  76. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  77. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  78. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  79. const logger = loggerFactory('growi:pages:all');
  80. const {
  81. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  82. } = pagePathUtils;
  83. const { removeHeadingSlash } = pathUtils;
  84. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  85. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  86. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  87. {
  88. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  89. return v?.data != null
  90. && v?.data.toObject != null
  91. && v?.meta != null
  92. && isIPageInfoForEntity(v.meta);
  93. },
  94. serialize: (v) => {
  95. return {
  96. data: superjson.stringify(v.data.toObject()),
  97. meta: superjson.stringify(v.meta),
  98. };
  99. },
  100. deserialize: (v) => {
  101. return {
  102. data: superjson.parse(v.data),
  103. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  104. };
  105. },
  106. },
  107. 'IPageToShowRevisionWithMetaTransformer',
  108. );
  109. const IdenticalPathPage = (): JSX.Element => {
  110. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  111. return <IdenticalPathPage />;
  112. };
  113. const PutbackPageModal = (): JSX.Element => {
  114. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  115. return <PutbackPageModal />;
  116. };
  117. type Props = CommonProps & {
  118. currentUser: IUser,
  119. pageWithMeta: IPageToShowRevisionWithMeta | null,
  120. // pageUser?: any,
  121. redirectFrom?: string;
  122. // shareLinkId?: string;
  123. isLatestRevision?: boolean,
  124. isIdenticalPathPage?: boolean,
  125. isForbidden: boolean,
  126. isNotFound: boolean,
  127. isNotCreatablePage: boolean,
  128. // isAbleToDeleteCompletely: boolean,
  129. templateTagData?: string[],
  130. templateBodyData?: string,
  131. isSearchServiceConfigured: boolean,
  132. isSearchServiceReachable: boolean,
  133. isSearchScopeChildrenAsDefault: boolean,
  134. isSlackConfigured: boolean,
  135. // isMailerSetup: boolean,
  136. isAclEnabled: boolean,
  137. // hasSlackConfig: boolean,
  138. drawioUri: string | null,
  139. hackmdUri: string,
  140. noCdn: string,
  141. // highlightJsStyle: string,
  142. isAllReplyShown: boolean,
  143. isContainerFluid: boolean,
  144. editorConfig: EditorConfig,
  145. isEnabledStaleNotification: boolean,
  146. isEnabledAttachTitleHeader: boolean,
  147. // isEnabledLinebreaks: boolean,
  148. // isEnabledLinebreaksInComments: boolean,
  149. adminPreferredIndentSize: number,
  150. isIndentSizeForced: boolean,
  151. disableLinkSharing: boolean,
  152. rendererConfig: RendererConfig,
  153. // UI
  154. userUISettings?: IUserUISettings
  155. // Sidebar
  156. sidebarConfig: ISidebarConfig,
  157. };
  158. const GrowiPage: NextPage<Props> = (props: Props) => {
  159. // const { t } = useTranslation();
  160. const router = useRouter();
  161. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  162. // register global EventEmitter
  163. if (isClient() && window.globalEmitter == null) {
  164. window.globalEmitter = new EventEmitter();
  165. }
  166. // commons
  167. useEditorConfig(props.editorConfig);
  168. useCsrfToken(props.csrfToken);
  169. useCustomizedLogoSrc(props.customizedLogoSrc);
  170. // UserUISettings
  171. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  172. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  173. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  174. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  175. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  176. // page
  177. useIsLatestRevision(props.isLatestRevision);
  178. useIsContainerFluid(props.isContainerFluid);
  179. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  180. useIsForbidden(props.isForbidden);
  181. useIsNotFound(props.isNotFound);
  182. // useIsNotCreatable(props.IsNotCreatable);
  183. useRedirectFrom(props.redirectFrom);
  184. // useShared();
  185. // useShareLinkId(props.shareLinkId);
  186. useIsSharedUser(false); // this page cann't be routed for '/share'
  187. useIsIdenticalPath(false); // TODO: need to initialize from props
  188. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  189. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  190. useIsSearchPage(false);
  191. useTemplateTagData(props.templateTagData);
  192. useTemplateBodyData(props.templateBodyData);
  193. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  194. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  195. useIsSearchServiceReachable(props.isSearchServiceReachable);
  196. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  197. useIsSlackConfigured(props.isSlackConfigured);
  198. // useIsMailerSetup(props.isMailerSetup);
  199. useIsAclEnabled(props.isAclEnabled);
  200. // useHasSlackConfig(props.hasSlackConfig);
  201. useDrawioUri(props.drawioUri);
  202. useHackmdUri(props.hackmdUri);
  203. // useNoCdn(props.noCdn);
  204. useDefaultIndentSize(props.adminPreferredIndentSize);
  205. useIsIndentSizeForced(props.isIndentSizeForced);
  206. useDisableLinkSharing(props.disableLinkSharing);
  207. useRendererConfig(props.rendererConfig);
  208. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  209. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  210. useIsAllReplyShown(props.isAllReplyShown);
  211. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  212. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  213. const { pageWithMeta, userUISettings } = props;
  214. const pageId = pageWithMeta?.data._id;
  215. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  216. useCurrentPageId(pageId ?? null);
  217. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  218. useCurrentPathname(props.currentPathname);
  219. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  220. useEditingMarkdown(pageWithMeta?.data.revision?.body);
  221. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  222. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  223. const { getClassNamesByEditorMode } = useEditorMode();
  224. const shouldRenderPutbackPageModal = pageWithMeta != null
  225. ? _isTrashPage(pageWithMeta.data.path)
  226. : false;
  227. // sync grant data
  228. useEffect(() => {
  229. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  230. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  231. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  232. useEffect(() => {
  233. const decodedURI = decodeURI(window.location.pathname);
  234. if (isClient() && decodedURI !== props.currentPathname) {
  235. router.replace(props.currentPathname, undefined, { shallow: true });
  236. }
  237. }, [props.currentPathname, router]);
  238. const classNames: string[] = [];
  239. const isSidebar = pagePath === '/Sidebar';
  240. classNames.push(...getClassNamesByEditorMode(isSidebar));
  241. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  242. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  243. ? null
  244. : currentPage.expandContentWidth;
  245. const isContainerFluidDefault = props.isContainerFluid;
  246. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  247. return (
  248. <>
  249. <Head>
  250. {/*
  251. {renderScriptTagByName('drawio-viewer')}
  252. {renderScriptTagByName('highlight-addons')}
  253. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  254. */}
  255. </Head>
  256. <DrawioViewerScript />
  257. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  258. <div className="h-100 d-flex flex-column justify-content-between">
  259. <header className="py-0 position-relative">
  260. <div id="grw-subnav-container">
  261. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  262. </div>
  263. </header>
  264. <div className="d-edit-none">
  265. <GrowiSubNavigationSwitcher />
  266. </div>
  267. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  268. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  269. <div className="flex-grow-1">
  270. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  271. <div id="content-main" className="content-main grw-container-convertible">
  272. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  273. { !props.isIdenticalPathPage && (
  274. <>
  275. <PageAlerts />
  276. { props.isForbidden && <ForbiddenPage /> }
  277. { props.isNotCreatablePage && <NotCreatablePage />}
  278. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  279. {/* <DisplaySwitcher /> */}
  280. {/* <PageStatusAlert /> */}
  281. </>
  282. ) }
  283. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  284. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  285. <div id="revision-toc-content" className="revision-toc-content"></div>
  286. </div>
  287. </div> */}
  288. </div>
  289. </div>
  290. </div>
  291. { !props.isIdenticalPathPage && !props.isNotFound && (
  292. <footer className="footer d-edit-none">
  293. { pageWithMeta != null && pagePath != null && !isTopPagePath && (
  294. <Comments pageId={pageId} pagePath={pagePath} revision={pageWithMeta.data.revision} />
  295. ) }
  296. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  297. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  298. ) }
  299. <CurrentPageContentFooter />
  300. </footer>
  301. )}
  302. <UnsavedAlertDialog />
  303. <DescendantsPageListModal />
  304. <HandsontableModal />
  305. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  306. </div>
  307. </BasicLayout>
  308. </>
  309. );
  310. };
  311. function getPageIdFromPathname(currentPathname: string): string | null {
  312. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  313. }
  314. class MultiplePagesHitsError extends ExtensibleCustomError {
  315. pagePath: string;
  316. constructor(pagePath: string) {
  317. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  318. this.pagePath = pagePath;
  319. }
  320. }
  321. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  322. const { model: mongooseModel } = await import('mongoose');
  323. const req: CrowiRequest = context.req as CrowiRequest;
  324. const { crowi } = req;
  325. const { revisionId } = req.query;
  326. const Page = crowi.model('Page') as PageModel;
  327. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  328. const { pageService } = crowi;
  329. let currentPathname = props.currentPathname;
  330. const pageId = getPageIdFromPathname(currentPathname);
  331. const isPermalink = _isPermalink(currentPathname);
  332. const { user } = req;
  333. if (!isPermalink) {
  334. // check redirects
  335. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  336. if (chains != null) {
  337. // overwrite currentPathname
  338. currentPathname = chains.end.toPath;
  339. props.currentPathname = currentPathname;
  340. // set redirectFrom
  341. props.redirectFrom = chains.start.fromPath;
  342. }
  343. // check whether the specified page path hits to multiple pages
  344. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  345. if (count > 1) {
  346. throw new MultiplePagesHitsError(currentPathname);
  347. }
  348. }
  349. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  350. const page = pageWithMeta?.data as unknown as PageDocument;
  351. // add user to seen users
  352. if (page != null && user != null) {
  353. await page.seen(user);
  354. }
  355. // populate & check if the revision is latest
  356. if (page != null) {
  357. page.initLatestRevisionField(revisionId);
  358. await page.populateDataToShowRevision();
  359. props.isLatestRevision = page.isLatestRevision();
  360. }
  361. if (page == null && user != null) {
  362. const templateData = await Page.findTemplate(props.currentPathname);
  363. if (templateData != null) {
  364. props.templateTagData = templateData.templateTags as string[];
  365. props.templateBodyData = templateData.templateBody as string;
  366. }
  367. }
  368. props.pageWithMeta = pageWithMeta;
  369. }
  370. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  371. const { model: mongooseModel } = await import('mongoose');
  372. const req = context.req as CrowiRequest<IUserHasId & any>;
  373. const { user } = req;
  374. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  375. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  376. if (userUISettings != null) {
  377. props.userUISettings = userUISettings.toObject();
  378. }
  379. }
  380. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  381. const req: CrowiRequest = context.req as CrowiRequest;
  382. const { crowi } = req;
  383. const Page = crowi.model('Page') as PageModel;
  384. const { currentPathname } = props;
  385. const pageId = getPageIdFromPathname(currentPathname);
  386. const isPermalink = _isPermalink(currentPathname);
  387. const page = props.pageWithMeta?.data;
  388. if (props.isIdenticalPathPage) {
  389. // TBD
  390. }
  391. else if (page == null) {
  392. props.isNotFound = true;
  393. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  394. // check the page is forbidden or just does not exist.
  395. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  396. props.isForbidden = count > 0;
  397. }
  398. else {
  399. props.isNotFound = page.isEmpty;
  400. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  401. if (isPermalink && page.isEmpty) {
  402. props.currentPathname = page.path;
  403. }
  404. // /path/to/page ==> /62a88db47fed8b2d94f30000
  405. if (!isPermalink && !page.isEmpty) {
  406. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  407. if (!isToppage) {
  408. props.currentPathname = `/${page._id}`;
  409. }
  410. }
  411. }
  412. }
  413. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  414. // const req: CrowiRequest = context.req as CrowiRequest;
  415. // const { crowi } = req;
  416. // const UserModel = crowi.model('User');
  417. // if (isUserPage(props.currentPagePath)) {
  418. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  419. // if (user != null) {
  420. // props.pageUser = JSON.stringify(user.toObject());
  421. // }
  422. // }
  423. // }
  424. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  425. const req: CrowiRequest = context.req as CrowiRequest;
  426. const { crowi } = req;
  427. const {
  428. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  429. } = crowi;
  430. props.isSearchServiceConfigured = searchService.isConfigured;
  431. props.isSearchServiceReachable = searchService.isReachable;
  432. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  433. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  434. // props.isMailerSetup = mailService.isMailerSetup;
  435. props.isAclEnabled = aclService.isAclEnabled();
  436. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  437. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  438. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  439. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  440. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  441. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  442. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  443. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  444. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  445. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  446. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  447. props.editorConfig = {
  448. upload: {
  449. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  450. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  451. },
  452. };
  453. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  454. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  455. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  456. props.rendererConfig = {
  457. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  458. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  459. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  460. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  461. plantumlUri: process.env.PLANTUML_URI ?? null,
  462. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  463. // XSS Options
  464. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  465. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  466. tagWhiteList: crowi.xssService.getTagWhiteList(),
  467. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  468. };
  469. props.sidebarConfig = {
  470. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  471. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  472. };
  473. }
  474. /**
  475. * for Server Side Translations
  476. * @param context
  477. * @param props
  478. * @param namespacesRequired
  479. */
  480. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  481. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  482. props._nextI18Next = nextI18NextConfig._nextI18Next;
  483. }
  484. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  485. const req = context.req as CrowiRequest<IUserHasId & any>;
  486. const { user } = req;
  487. const result = await getServerSideCommonProps(context);
  488. // check for presence
  489. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  490. if (!('props' in result)) {
  491. throw new Error('invalid getSSP result');
  492. }
  493. const props: Props = result.props as Props;
  494. if (props.redirectDestination != null) {
  495. return {
  496. redirect: {
  497. permanent: false,
  498. destination: props.redirectDestination,
  499. },
  500. };
  501. }
  502. if (user != null) {
  503. props.currentUser = user.toObject();
  504. }
  505. try {
  506. await injectPageData(context, props);
  507. }
  508. catch (err) {
  509. if (err instanceof MultiplePagesHitsError) {
  510. props.isIdenticalPathPage = true;
  511. }
  512. else {
  513. throw err;
  514. }
  515. }
  516. await injectUserUISettings(context, props);
  517. await injectRoutingInformation(context, props);
  518. injectServerConfigurations(context, props);
  519. await injectNextI18NextConfigurations(context, props, ['translation']);
  520. return {
  521. props,
  522. };
  523. };
  524. export default GrowiPage;